package com.edu.web.fliter;

import com.edu.entity.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter("/*")
public class Filter implements javax.servlet.Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        // 转化
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;

        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json;charset=UTF-8");

        String url = req.getRequestURL().toString();
        System.out.println(url);
        // 允许无条件访问的路径列表
        String[] urls = {
                "/login.jsp",
                "/loginServlet",
                "/register.jsp",
                "/registerUserServlet",
                "/index.jsp",
                "/rent.jsp",
                "/selectVehiclesServlet",
                "/images",
                "/css",
                "/js"
        };
        for (String s : urls) {
            // 如果是允许访问的URL直接放行
            if (url.contains(s)) {
                filterChain.doFilter(req, resp);
                return;
            }
        }

        // 判断是否登录
        HttpSession session = req.getSession();
        User user = (User) session.getAttribute("user");
        if (user != null) {
            // 已登录，放行
            filterChain.doFilter(req, resp);
        } else {
            // 未登录，跳转到登录页面
            resp.sendRedirect("/car_rental/u/page/login.jsp");
        }
    }
}
